import storage from 'store'
import expirePlugin from 'store/plugins/expire'
import { isLogin, login, getInfo, logout, checkToken as checkTokenApi, getUserInfo as getUserInfoApi, checkPermission as checkPermissionApi } from '@/api/login'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { removeUrlSearch, goSsoLogin } from '@/utils/util'
import { message } from 'ant-design-vue';
import Router from '@/router';

storage.addPlugin(expirePlugin)
const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      // state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {
    // 验证token
    checkToken({ commit }, params) {
      return new Promise((resolve, reject) => {
        checkTokenApi(params).then(async response => {
          if (response.code == 200) {
            removeUrlSearch();
            Router.push('/product/list')
          } else {
            message.error('ticket验证失败')
            goSsoLogin()
            return
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 是否登录
    isLogin({ commit }) {
      return new Promise((resolve, reject) => {
        if (sessionStorage.getItem('isLogin') == 1) {
          resolve(1)
        } else{
          isLogin().then(response => {
            sessionStorage.setItem('isLogin', +response.success)
            resolve(response.success)
          }).catch(error => {
            reject(error)
          })
        }
      })
    },
    // 登录
    Login({ commit }, userInfo) {
      console.log('login', userInfo)
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          if(response.code == 200){
            window.localStorage.setItem('name', userInfo.name)
            resolve()
          } else{
            reject(response)
          }
          
          // const result = response.result
          // storage.set(ACCESS_TOKEN, result.token, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
          // commit('SET_TOKEN', result.token)
          // resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        // 请求后端获取用户信息 /api/user/info
        getInfo().then(response => {
          const { result } = response
          if (result.role && result.role.permissions.length > 0) {
            const role = { ...result.role }
            role.permissions = result.role.permissions.map(permission => {
              const per = {
                ...permission,
                actionList: (permission.actionEntitySet || {}).map(item => item.action)
              }
              return per
            })
            role.permissionList = role.permissions.map(permission => { return permission.permissionId })
            // 覆盖响应体的 role, 供下游使用
            result.role = role

            commit('SET_ROLES', role)
            commit('SET_INFO', result)
            commit('SET_NAME', { name: result.name, welcome: welcome() })
            commit('SET_AVATAR', result.avatar)
            // 下游
            resolve(result)
          } else {
            reject(new Error('getInfo: roles must be a non-null array !'))
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout({ commit, state }) {
      return new Promise(async (resolve) => {
        const res = await getUserInfoApi();
        logout({ loginId: res.data.id }).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          storage.remove(ACCESS_TOKEN)
          resolve()
        }).catch((err) => {
          console.log('logout fail:', err)
          // resolve()
        }).finally(() => {
        })
      })
    }

  }
}

export default user
